1.用命令新建policy:
php artisan make:policy PostPolicy
2.在app/Policies/PostPolicy.php中添加处理文件的权限的方法:
//修改: public function update(User $user, Post $post) { return $user->id == $post->user_id; } //删除权限: public function delete(User $user, Post $post) { return $user->id == $post->user_id; }
控制器中,添加权限限制:
//更新文章: public function update(Post $post) { //验证: $this->validate(request(), [ 'title' => 'required|string|max:100|min:10', 'content' => 'required|string|min:4' ]); $this->authorize('update', $post); //逻辑: $post->title = \request('title'); $post->content = \request('content'); $post->save(); return redirect("/posts/{$post->id}"); } //删除逻辑: public function delete(Post $post) { $this->authorize('delete', $post); //TODD 用户的权限验证: $post->delete(); return redirect("/posts"); }
在视图中,对授权的使用: